package com.liujiajin.controller;

import com.alibaba.fastjson.JSON;
import com.liujiajin.param.AddSensitiveWordParam;
import com.liujiajin.param.BaseResult;
import com.liujiajin.dto.SensitiveWordDto;
import com.liujiajin.service.ISensitiveService;
import com.liujiajin.utils.BaseResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/sensitivewords")
@Slf4j
public class SensitiveWordsController {

    @Autowired
    private ISensitiveService sensitiveService;

    @RequestMapping(value="/add",method = RequestMethod.POST)
    public BaseResult<Boolean> addWord(@RequestBody AddSensitiveWordParam param){
        try{
            log.info("添加敏感词-controller-addWord-入参:{}", JSON.toJSONString( param));
            checkParam(param);
            SensitiveWordDto dto = new SensitiveWordDto();
            dto.setWord(param.getWord());
            dto.setCategory(param.getCategory());
            int count = sensitiveService.insert(dto);
            log.info("添加敏感词-controller-addWord-出参:{}",count>0);
            return BaseResultUtils.generateSuccess(count>0);
        }catch (Exception e){
            log.error("添加敏感词-controller-addWord-异常:{}",e);
            return BaseResultUtils.generateFail("添加敏感词失败");
        }
    }
    /**
     * 校验入参
     * @param param
     */
    private void checkParam(AddSensitiveWordParam param) {
        Assert.isTrue(param!=null,"入参不能为空");
        Assert.isTrue(!StringUtils.isEmpty(param.getWord()),"敏感词不能为空");
        Assert.isTrue(!StringUtils.isEmpty(param.getCategory()),"敏感词分类不能为空");
    }

}
